package com.ebupt.migu.music.schedule;

import com.ebupt.migu.music.autoTri.util.MethodService;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.schedule.service.EffectStatisticService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.time.LocalDate;
import java.util.concurrent.TimeUnit;

/**
 * 统计定时执行任务类
 *
 * @author xuhongsong@cd.ebupt.com
 * @version 1.0
 * @className EffectStatisticTask
 * @date 2020/7/6 9:46
 */
@Slf4j
@Component
@EnableScheduling
public class EffectStatisticTask {

    // 相关/无关统计服务层
    @Autowired
    private EffectStatisticService effectStatisticService;
    @Autowired
    private MethodService methodService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 短信策略： 立即进行消息通知 晚上一点的时候执行一次定时任务
     */
    @Scheduled(cron = "${cron.message_notice}")
    public void sendEffectStatistic() {
        String today = DateUtil.getDateToday();
        String redis_lock_key = "message_notice_" + today;
        if (redisTemplate.hasKey(redis_lock_key)) {
            return;
        }
        redisTemplate.opsForValue().set(redis_lock_key, today, 60 * 60 * 48, TimeUnit.SECONDS);
        Boolean IsAllow = methodService.anotherMethod(2, 1);
        if (IsAllow) {
            log.info("执行有关统计开始");
            try {
                // 取昨天日期
                String yesterday = LocalDate.now().minusDays(1).toString();
                log.info("执行日期:" + yesterday);
                // 由于负载原因，可能导致该任务执行2次或以上，造成数据异常，因此查询源数据最新日期是否为昨天，然后判断是否向下执行
                if (effectStatisticService.queryNewDate(yesterday)) {
                    effectStatisticService.RelatedStatistics(yesterday);
                    log.info("执行有关统计结束");
                    log.info("执行无关统计开始");
                    effectStatisticService.UnRelatedStatistics(yesterday);
                    log.info("执行无关统计结束");
                    log.info("统计进入总表开始");
                    effectStatisticService.update(yesterday);
                    effectStatisticService.updateAuto(yesterday);
                    log.info("统计进入总表结束");
                    log.info("统计转化率开始");
                    effectStatisticService.updateConversionRate();
                    log.info("统计转化率结束");
                }
            } catch (ParseException e) {
                log.info("ParseException异常");
                e.printStackTrace();
            } finally {

                methodService.anotherMethod(1, 2);
            }
            log.info("执行有关统计结束");
        }
    }
}
